package ren.steve.system.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.*;
import ren.steve.annotation.Log;
import ren.steve.common.result.HttpStatus;
import ren.steve.common.result.Result;
import ren.steve.common.utils.FormatDateUtil;
import ren.steve.common.utils.MD5;
import ren.steve.enums.BusinessType;
import ren.steve.model.system.bean.SystemRole;
import ren.steve.model.system.bean.SystemUser;
import ren.steve.model.system.bean.SystemUserRole;
import ren.steve.model.system.vo.SystemUserQueryVo;
import ren.steve.system.service.SystemRoleService;
import ren.steve.system.service.SystemUserRoleService;
import ren.steve.system.service.SystemUserService;

import java.io.Serializable;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;

/**
 * @Author: LiuGuoJia
 * @Description:
 * @Date: Created in 2024/1/18 16:23
 * @URL: http://127.0.0.1:9900/api/system/system-user
 * @SwaggerURL: http://127.0.0.1:9900/doc.html
 */

@Api(tags = "APIs-用户管理")
@CrossOrigin
@RestController
@RequestMapping("/api/system/system-user")
public class SystemUserController {

  @Autowired
  private SystemUserService systemUserService;

  @Autowired
  private SystemRoleService systemRoleService;

  @Autowired
  private SystemUserRoleService systemUserRoleService;

  @ApiOperation("API-查询所有")
  @Log(title = "查询所有", businessType = BusinessType.GET)
  @PreAuthorize("hasAuthority('/api/system/system-user/list')")
  @GetMapping("list")
  public Result findList () {
    List<SystemUser> users = systemUserService.list();
    return Result.ok(users, HttpStatus.OK);
  }

  @ApiOperation("API-根据ID查询单条数据")
  @Log(title = "根据ID查询单条数据", businessType = BusinessType.GET)
  @PreAuthorize("hasAuthority('/api/system/system-user/detail')")
  @GetMapping("/detail")
  public Result findById (String id) {
    // 手动抛出异常操作
    // try {
    //   int i = 9/0;
    // } catch (Exception e) {
    //   throw new CustomException(2001, "自定义异常处理!");
    // }
    // 根据ID获取用户数据
    SystemUser user = systemUserService.getById(id);
    // 根据 user id 获取用户角色 ids
    List<String> roleIds = systemUserRoleService.getSystemRoleByUserId(id);
    if (!roleIds.isEmpty()) {
      // 根据 角色 ids 获取角色数据
      List<SystemRole> roles = systemRoleService.listByIds(roleIds);
      user.setRoles(roles);
    } else {
      user.setRoles(new ArrayList<>());
    }
    return Result.ok(user, HttpStatus.OK);
  }

  @ApiOperation("API-条件分页查询")
  @Log(title = "条件分页查询", businessType = BusinessType.GET)
  @PreAuthorize("hasAuthority('/api/system/system-user/list/query')")
  @GetMapping("list/query")
  public Result findListPage (SystemUserQueryVo vo) {
    // 创建配置对象
    int page = 1;
    int pageSize = 20;
    if (vo.getPage() != null) {
      page = vo.getPage();
    }
    if (vo.getPageSize() != null) {
      pageSize = vo.getPageSize();
    }
    Page<SystemUser> pagination = new Page<>(page, pageSize);
    // 调用 Service 方法
    IPage<SystemUser> model = systemUserService.select(pagination, vo);
    return Result.ok(model, HttpStatus.OK);
  }

  @ApiOperation("API-添加一条数据")
  @Log(title = "添加一条数据", businessType = BusinessType.INSERT)
  @PreAuthorize("hasAuthority('/api/system/system-user/save')")
  @PostMapping("save")
  public Result save (@RequestBody SystemUser user) {
    boolean success;
    String encrypt = MD5.encrypt(user.getPassword());
    user.setPassword(encrypt);
    user.setGmtCreate(FormatDateUtil.helperFormatDate("yyyy-MM-dd HH:mm:ss", new Date()));
    user.setGmtUpdate(FormatDateUtil.helperFormatDate("yyyy-MM-dd HH:mm:ss", new Date()));
    success = systemUserService.save(user);
    if (success) {
      return Result.ok(null, HttpStatus.OK);
    }
    return Result.fail();
  }

  @ApiOperation("API-修改数据")
  @Log(title = "修改数据", businessType = BusinessType.UPDATE)
  @PreAuthorize("hasAuthority('/api/system/system-user/update')")
  @PostMapping("update")
  public Result update (@RequestBody SystemUser user) {
    user.setGmtUpdate(FormatDateUtil.helperFormatDate("yyyy-MM-dd HH:mm:ss", new Date()));
    boolean success = systemUserService.updateById(user);
    if (success) {
      return Result.ok(null, HttpStatus.OK);
    }
    return Result.fail();
  }

  @ApiOperation("API-根据ID删除")
  @Log(title = "根据ID删除", businessType = BusinessType.DELETE)
  @PreAuthorize("hasAuthority('/api/system/system-user/delete')")
  @DeleteMapping("delete/{id}")
  public Result deleteById (@PathVariable String id) {
    boolean success = systemUserService.removeById(id);
    if (success) {
      return Result.ok(null, HttpStatus.OK);
    }
    return Result.fail();
  }

  @ApiOperation("API-根据多个ID批量删除")
  @Log(title = "根据多个ID批量删除", businessType = BusinessType.DELETE)
  @PreAuthorize("hasAuthority('/api/system/system-user/delete')")
  @DeleteMapping("delete")
  public Result deleteByIds (@RequestBody List<String> ids) {
    boolean success = systemUserService.removeByIds(ids);
    if (success) {
      return Result.ok(null, HttpStatus.OK);
    }
    return Result.fail();
  }

  @ApiOperation("API-根据UserID设置角色 roleIds")
  @Log(title = "根据UserID设置角色", businessType = BusinessType.UPDATE)
  @PreAuthorize("hasAuthority('/api/system/system-user/authorization')")
  @PostMapping("authorization")
  public Result authorization (@RequestBody Map<String, Object> map) {
    // 根据ID获取用户数据
    SystemUser user = systemUserService.getById((Serializable) map.get("userId"));
    if (user == null) {
      return Result.fail(HttpStatus.NOT_USER_EXIST);
    } else {
      // 先删除用户所有授权
      String userId = (String) map.get("userId");
      QueryWrapper<SystemUserRole> wrapper = new QueryWrapper<>();
      wrapper.eq("user_id", userId);
      systemUserRoleService.remove(wrapper);
      // 再添加改变的授权
      List<SystemUserRole> userRoles = new ArrayList<>();
      List<String> roleIds = (List<String>) map.get("roleIds");
      if (!roleIds.isEmpty()) {
        for (String roleId : roleIds ) {
          SystemUserRole userRole = new SystemUserRole();
          userRole.setUserId(userId);
          userRole.setRoleId(roleId);
          userRoles.add(userRole);
        }
        systemUserRoleService.saveBatch(userRoles);
      }
    }
    boolean success = true;
    if (success) {
      return Result.ok(null, HttpStatus.OK);
    }
    return Result.fail();
  }
}
